package com.wrh.springboot.restwrap;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author wrh
 */
@Slf4j
@Configuration()
@ConditionalOnProperty(prefix = "rest-wrap", value = "enabled", havingValue = "true",matchIfMissing = true)
@EnableConfigurationProperties(RestResultConfig.class)
public class RestResultResponseAutoConfiguration implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;
    private final RestResultConfig restResultConfig;

    public RestResultResponseAutoConfiguration(ObjectMapper objectMapper, RestResultConfig restResultConfig) {
        this.objectMapper = objectMapper;
        this.restResultConfig = restResultConfig;
    }

    @Bean
    public RestResultAdvice restResultAdvice() {
        return new RestResultAdvice(objectMapper,restResultConfig);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] swaggerExcludes=new String[]{"/doc.html","/swagger-ui.html","/swagger-resources/**","/webjars/**","/v3/**"};
        registry.addInterceptor(new CustomHandlerInterceptor(objectMapper,restResultConfig))
                .addPathPatterns(restResultConfig.getAddPathPatterns().split(","))
                .excludePathPatterns(swaggerExcludes)
                .excludePathPatterns(restResultConfig.getExcludePathPatterns().split(","));
        log.debug("拦截器 CustomHandlerInterceptor 注册成功");
    }

    // 在所有的 HttpMessageConverter 实例集合中，StringHttpMessageConverter 要比其它的 Converter 排得靠前一些。我们需要将处理 Object 类型的 HttpMessageConverter 放得靠前一些
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0, new MappingJackson2HttpMessageConverter());
    }
}
